//公告列表
import React, {Component} from 'react'
import {View, Text, FlatList, TouchableOpacity} from 'react-native'
import Loading from '../common/loading'
import styles from "../../configs/styles";
import {I18n} from "../../configs/enumeration";
import {GetBroadcastsApi} from "../../configs/api";

class broadcastList extends Component {

  //初始化props和state
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      loading: true,
      page: 1,
      flipping: false
    }
  }

  componentDidMount() {
    this.getData()
  }

  getData = () => {
    GetBroadcastsApi(this.state.page).then((data) => {
      let _data = this.state.data;
      _data.push(...data.broadcasts);
      this.setState({
        data: _data,
        loading: false,
        flipping: false
      })
    })
  };

  refresh = () => {
    this.setState({
      page: 1,
      data: []
    }, () => {
      this.getData()
    })
  };

  //翻页
  Flip = () => {
    if (this.state.flipping) return;
    this.setState({flipping: true, page: this.state.page + 1}, () => {
      this.getData()
    })
  };

  //用于给FlatList的每一条item指定一个key
  _keyExtractor = (item, index) => index;

  //每一条item的模板
  _renderItem = ({item}) => {
    return (
      <TouchableOpacity style={styles.itemContainer} onPress={() => {
        this.props.navigation.navigate('broadcastShow', {broadcast_id: item.id})
      }}>
        <View style={{backgroundColor: item.color, padding: 10}}>
          <Text></Text>
        </View>
        <View style={{flex: 1, marginLeft: 10}}>
          <View style={{alignItems: 'center'}}><Text>{item.title}</Text></View>
          <View style={{flexDirection: 'row', flex: 1}}>
            <View style={{flex: 1}}><Text>{item.department_name}</Text></View>
            <View><Text>{item.created_at}</Text></View>
          </View>
          <View><Text>{item.content}</Text></View>
        </View>
      </TouchableOpacity>
    )
  };

  render() {
    const {loading, data} = this.state;
    if (loading) {
      return <Loading/>
    } else {
      return (
        <View bounces={false} style={{flex: 1}}>
          <FlatList
            data={data}
            extraData={this.state}
            keyExtractor={this._keyExtractor}
            renderItem={this._renderItem}
            refreshing={loading}
            onRefresh={this.refresh}
            onEndReachedThreshold={0.1}
            onEndReached={this.Flip}
          />
        </View>
      )
    }

  }

}

export default broadcastList